<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>抄表列表</title>

  </head>
  <body>
    <script type="text/javascript">
      var waterMeterDS;
      Ext.onReady(function(){
        Ext.QuickTips.init();
        Ext.BLANK_IMAGE_URL = '/javascripts/ext/resources/images/default/s.gif';
        
        //抄表搜索表单
        var buildingUnitTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:90px">{number}</div><div>{name}</div>', '</div></tpl>');
        var buildingUnitStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/building/getHighBuildingUnits"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }, {
              name: 'number'
            }])
        });
        //供应商
        var buildingUnit = new Ext.form.ComboBox({
          width:350,
          store: buildingUnitStore,
          fieldLabel: '楼座单元',
          allowBlank: false,
          blankText: "楼座单元必须选择",
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'building_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择楼座单元...',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          //hideTrigger: false,
          //readOnly:true,
          tpl: buildingUnitTemplate,
          minChars: 3,
          editable: true,
          mode: 'remote',
          triggerAction: 'all',
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });
        
        var waterCurrentYear = new Ext.form.ComboBox({ //combobox
          name: 'current_year',
          fieldLabel: '抄表年',
          width: '90',
          resiable: true,
          typeAhead: true,
          allowBlank: false,
          handleHeight: 100, //
          displayField: 'key',
          valueField: 'value',
          mode: 'local',
          selectOnFocus: true,
          triggerAction: 'all',//这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
          emptyText: '选择年...',
          store: new Ext.data.Store({
            data: [['2004', '2004'],['2005', '2005'],['2006', '2006'],['2007', '2007'],['2008', '2008'], ['2009', '2009'], ['2010', '2010'], ['2011', '2011'], ['2012', '2012']],
            reader: new Ext.data.ArrayReader({
              id: 0
            }, [{
                name: 'value'
              }, {
                name: 'key'
              }])
          }), //数据储存到这个comboBox
          anchor: '90%'
        });
        waterCurrentYear.setValue(new Date().clearTime(true).getFullYear());

        var waterCurrentMonth = new Ext.form.ComboBox({ //combobox
          name: 'current_month',
          fieldLabel: '月',
          width: '90',
          resiable: true,
          typeAhead: true,
          allowBlank: false,
          handleHeight: 100, //
          displayField: 'key',
          valueField: 'value',
          selectOnFocus: true,
          mode: 'local',
          triggerAction: 'all',//这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
          emptyText: '选择月...',
          store: new Ext.data.Store({
            data: [['2', '2'], ['4', '4'], ['6', '6'], ['8', '8'],  ['10', '10'], ['12', '12']],
            reader: new Ext.data.ArrayReader({
              id: 0
            }, [{
                name: 'value'
              }, {
                name: 'key'
              }])
          }), //数据储存到这个comboBox
          anchor: '90%'
        });

        var tempMonth = new Date().getMonth();
        if(tempMonth%2==0){
          waterCurrentMonth.setValue(tempMonth);
        }else{
          waterCurrentMonth.setValue(tempMonth-1);
        }

        var searchWaterMeterButton = new Ext.Button({
          text: '查询业主',
          iconCls: 'finding',
          handler: function(){
            if (waterMeterFormPanel.form.isValid()) {
              waterMeterDS.removeAll();
              waterMeterDS.baseParams.building_id = buildingUnit.getValue();
              waterMeterDS.baseParams.year = waterCurrentYear.getValue();
              waterMeterDS.baseParams.month = waterCurrentMonth.getValue();
              waterMeterDS.load();
            }
          }
        })
        
        var waterMeterFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          labelWidth: 55,
          width: '750',
          title: '按单元搜索',
          labelAlign: 'right',
          frame : true,
          //url: '/water_meter/create',
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [buildingUnit]
                }, {
                  columnWidth: .12,
                  layout: 'form',
                  border: false,
                  items: [waterCurrentYear]
                }, {
                  columnWidth: .1,
                  layout: 'form',
                  border: false,
                  items: [waterCurrentMonth]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [searchWaterMeterButton]
                }]
            }]
        });

        
        //------------------------------业主水表抄表Grid-------------------------
        var waterMeterDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/water_meter/getWaterMeters'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            },{
              name: 'owner'
            },{
              name: 'phone'
            },{
              name: 'water_last_meter'
            },{
              name: 'meter',
              mapping: 'current_meter',
              convert:function(value,record){
                if(value==""){
                  return "0";
                }else{
                  return value;
                }
              }
            },{
              name: 'water_meter_id',
              mapping: 'water_meter_id',
              convert:function(value,record){
                if(value==""){
                  return 0;
                }else{
                  return value
                }
              }
            },{
              name: 'is_paid'
            },{
              name: 'is_locked'
            }, {
              name: 'created_at'
            }, {
              name: 'updated_at'
            }])
        });
        //house的CM
        var waterMeterCM = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),{
            id: 'common',
            header: '数据库编号',
            dataIndex: 'id',
            width: 30,
            hidden:true
          },{
            header: '业主编号',
            dataIndex: 'number',
            width: 70
          },{
            header: '业主姓名',
            dataIndex: 'owner',
            width: 70
          },{
            header: '电话',
            dataIndex: 'phone',
            width: 80
          },{
            header: '上次水表数',
            dataIndex: 'water_last_meter',
            width: 80
          },{
            header: '水表',
            dataIndex: 'meter',
            editor: new Ext.form.NumberField({
              fieldLabel: '本次抄表数',
              allowBlank: false,
              allowDecimals: false,
              allowNegative: false,
              enableKeyEvents:true,
              anchor: '90%'
            }),
            width: 80
          },{
            header: '交费情况',
            dataIndex: 'is_paid',
            renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
              if(value == 1){
                return "<font color=green>已交费</font>";
              }else{
                return "<font color=red>未交费</font>";
              }
            },
            width: 80
          },{
            header: '水表记录的ID',
            dataIndex: 'water_meter_id',
            width: 80,
            hidden:true
          },{
            header: '生成日期',
            dataIndex: 'created_at',
            renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
            width: 110
          },{
            header: '修改日期',
            dataIndex: 'updated_at',
            renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
            width: 110
          }
        ]);
        
        //抄表Grid
        var waterMeterGrid = new Ext.grid.EditorGridPanel({
          store: waterMeterDS,
          cm: waterMeterCM,
          clicksToEdit: 1,//单击即可编辑
          renderTo: 'water_meter_grid',
          //width: 830,
          height: 500,
          loadMask: true,
          //frame: true,
          collapsible: true,
          autoExpandColumn: 'common',
          title: '抄表列表',
          frame: false,
          bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: waterMeterDS,
            displayInfo: true,
            displayMsg: "显示第 {0} 条到 {1} 条记录，一共 {2} 条",
            emptyMsg: "没有记录"
          })
        });
        
        waterMeterGrid.on("afteredit", afterEdit,this);
        function afterEdit(obj){
          var record = obj.record;
          var modifiedFieldName = obj.field;//获取被修改的列
          var houseId = record.get("id");
          var waterMeterId = record.get("water_meter_id");
          var meter = record.get("meter");
          var lastMeter = record.get("water_last_meter");
          var isPaid = record.get("is_paid");
          if(isPaid == 1){
            Ext.MessageBox.show({
              title: '提示消息',
              msg: '此次抄表记录已经交费，不能再修改抄表数字。',
              buttons: Ext.MessageBox.OK,
              icon: Ext.MessageBox.INFO
            });
          }else{
            if(meter > lastMeter){
              saveOrUpdateWaterMeter(houseId,waterMeterId,meter);
            }else{
              Ext.MessageBox.show({
                title: '提示消息',
                msg: '本次抄表数，小于或等于上次水表数字，请从新检查。',
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.INFO
              });
            }
          }          
        }
        //waterMeterDS.load();
        //----------------------workbench--------------------------------------
        var waterMeterWorkbenchPanel = new Ext.Panel({
          //title: '查找业主',
          //width: 350,
          height:700,
          //html: '&lt;empty panel&gt;',
          //cls:'cellpadding:10',
          layout: {
            type:'vbox',
            align:'stretch'
          },
          defaults:{margins:'5 5 5 5'},
          //bodyStyle: 'padding:15px;align:center',
          //listeners: {
          //expand: showAgileDiagram
          //},
          items:[waterMeterFormPanel,waterMeterGrid]
        });
        waterMeterWorkbenchPanel.render("water_mete");
        function saveOrUpdateWaterMeter(houseId,waterMeterId,meter){
          Ext.Ajax.request({
            url : '/water_meter/saveOrUpdateWaterMeter',
            success : function (result, request) {
                
            },
            failure : function (result, request){
              Ext.MessageBox.alert("提示","保存水表数时通讯失败，请从新操作");
            },
            method : 'POST',
            params : {
              house_id : houseId,
              water_meter_id: waterMeterId,
              meter:meter,
              year: waterCurrentYear.getValue(),
              month: waterCurrentMonth.getValue(),
              authenticity_token: authToken.getValue()
            }
          });
        }
      })
    </script>
    <div id="water_mete"></div>
    <div id="water_meter_grid"></div>
  </body>
</html>
